package com.mt.system.service.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.github.pagehelper.PageHelper;
import com.mt.common.PagerInfo;
import com.mt.common.ServiceResult;
import com.mt.system.entity.RoleEntity;
import com.mt.system.entity.RoleMenuRelateEntity;
import com.mt.system.mapper.AdminRoleRelateEntityMapper;
import com.mt.system.mapper.RoleEntityMapper;
import com.mt.system.mapper.RoleMenuRelateEntityMapper;

@Component
public class RoleServiceModel {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RoleServiceModel.class);

    @Autowired
    private RoleEntityMapper roleEntityMapper;

    @Autowired
    private AdminRoleRelateEntityMapper adminRoleRelateEntityMapper;

    @Autowired
    private RoleMenuRelateEntityMapper roleMenuRelateEntityMapper;

    public ServiceResult<List<RoleEntity>> selectList(Map<String, Object> params, PagerInfo<?> pagerInfo) {
        Assert.notNull(this.roleEntityMapper, "Property 'roleEntityMapper' is required.");
        ServiceResult<List<RoleEntity>> result = new ServiceResult<List<RoleEntity>>();
        try {
            if (pagerInfo != null) {
                PageHelper.startPage(pagerInfo.getPageIndex(), pagerInfo.getPageSize());
            }

            result.setResult(this.roleEntityMapper.selectList(params));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[SupplierImageServiceImpl][findList]：query findList occur exception", e);
        }
        return result;
    }

    public ServiceResult<RoleEntity> selectInfo(Map<String, Object> params) {
        Assert.notNull(this.roleEntityMapper, "Property 'roleEntityMapper' is required.");
        ServiceResult<RoleEntity> result = new ServiceResult<RoleEntity>();
        RoleEntity roleEntity = null;
        try {
            roleEntity = this.roleEntityMapper.selectByPrimaryKey(params);
            if (roleEntity != null) {
                Map<String, Object> roleMenuParams = new HashMap<String, Object>();
                roleMenuParams.put("roleId", roleEntity.getRoleId());
                List<RoleMenuRelateEntity> roleMenuList = roleMenuRelateEntityMapper.selectList(roleMenuParams);
                roleEntity.setRoleMenuList(roleMenuList);
            }
            result.setResult(roleEntity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[RoleServiceModel][selectInfo]：query selectInfo occur exception", e);
        }
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ServiceResult<Integer> insert(RoleEntity roleEntity) {
        Assert.notNull(this.roleEntityMapper, "Property 'roleEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        try {
            int save = this.roleEntityMapper.insert(roleEntity);
            if (save > 0) {
                id = roleEntity.getRoleId();
                List<RoleMenuRelateEntity> roleMenuList = roleEntity.getRoleMenuList();
                if (roleMenuList != null && roleMenuList.size() > 0) {
                    for (RoleMenuRelateEntity entity : roleMenuList) {
                        entity.setRoleId(id);
                    }
                    roleMenuRelateEntityMapper.insertList(roleMenuList);
                }
            }
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[RoleServiceModel][insert]：query insert occur exception", e);
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public ServiceResult<Integer> updateByPrimaryKeySelective(RoleEntity roleEntity) {
        Assert.notNull(this.roleEntityMapper, "Property 'roleEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        int id = 0;
        try {
            int save = this.roleEntityMapper.updateByPrimaryKeySelective(roleEntity);
            if (save > 0) {
                id = roleEntity.getRoleId();
                // 编辑操作，先删除原有用户角色关联数据，再创建
                roleMenuRelateEntityMapper.deleteByPrimaryKey(id);
                List<RoleMenuRelateEntity> roleMenuList = roleEntity.getRoleMenuList();
                if (roleMenuList != null && roleMenuList.size() > 0) {
                    roleMenuRelateEntityMapper.insertList(roleMenuList);
                }
            }
            result.setResult(id);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[RoleServiceModel][updateByPrimaryKeySelective]:query update occur exception", e);
            throw new RuntimeException(e.getMessage());
        }
        return result;
    }

    public ServiceResult<Integer> deleteByPrimaryKey(Integer roleId) {
        Assert.notNull(this.roleEntityMapper, "Property 'roleEntityMapper' is required.");
        ServiceResult<Integer> result = new ServiceResult<Integer>();
        Map<String, Object> params = null;
        try {
            // 删除前判断角色下面是否有关联用户，如果有，则不允许删除
            params = new HashMap<String, Object>();
            params.put("roleId", roleId);
            Integer userCount = adminRoleRelateEntityMapper.selectCount(params);
            if (userCount > 0) {
                result.setSuccess(false);
                result.setMessage("角色下还有关联的管理员，不能删除!");
                return result;
            }
            int save = this.roleEntityMapper.deleteByPrimaryKey(roleId);
            result.setResult(save);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("Unknown error!");
            LOGGER.error("[RoleServiceModel][deleteByPrimaryKey]:query update occur exception", e);
        }
        return result;
    }
}
